from flask import Flask, request, render_template, Response
from flask_cors import CORS
import ollama
import time

app = Flask(__name__, template_folder="templates")
CORS(app, resources={r"/*": {"origins": "*"}})

chat_history = []  # 存储对话历史

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/chat", methods=["GET"])
def chat():
    user_message = request.args.get("message", "")

    chat_history.append({"role": "user", "content": user_message})  # 记录用户输入

    def generate():
        response_stream = ollama.chat(
            model="deepseek-r1:32b",
            messages=chat_history,
            stream=True
        )

        full_response = ""
        for chunk in response_stream:
            text = chunk["message"]["content"]
            full_response += text
            yield f"data: {text}\n\n"  # SSE 格式
            time.sleep(0.03)

        chat_history.append({"role": "assistant", "content": full_response})  # 记录 AI 输出

    return Response(generate(), content_type="text/event-stream")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)
